package com.joshondesign.sdljava.gfx;

import com.joshondesign.sdljava.SDL;
import com.joshondesign.sdljava.SDL_PixelFormat;
import com.joshondesign.sdljava.SDL_Surface;
import com.joshondesign.sdljava.demo.PhotoTest;
import com.joshondesign.sdljava.gfx.effects.ImageFilter;

/**
* Created by IntelliJ IDEA.
* User: josh
* Date: 9/14/11
* Time: 2:30 AM
* To change this template use File | Settings | File Templates.
*/
public class FilterNode extends Node {
    SBuffer buffer;
    private final ImageFilter filter;
    private final Object source;

    public FilterNode(ImageFilter filter, Object source) {
        this.filter = filter;
        this.source = source;
    }

    @Override
    public void draw(GFX gfx) {
        SDL_Surface isurface = null;
        boolean  wasDirty = false;
        if(source instanceof SImage) {
            isurface = (SDL_Surface) ((SImage) source).getNative();
        }
        if(source instanceof FilterNode) {
            FilterNode src = (FilterNode) source;
            if(src.filter.isDirty() || src.buffer == null) {
                src.draw(gfx);
                wasDirty = true;
            }
            isurface = src.buffer.getNative();
        }
        if(buffer == null || filter.isDirty() || wasDirty) {
            filter.setClean();
            if(buffer == null) {
                buffer = gfx.createBuffer(isurface.getW(), isurface.getH());
            }
            SDL_Surface bsurface = (SDL_Surface) buffer.getNative();
            SDL_PixelFormat format = isurface.getFormat();
            SDL_PixelFormat bformat = bsurface.getFormat();
            for(int x=0; x<buffer.getWidth(); x++) {
                for(int y=0; y<buffer.getHeight(); y++) {
                    long color = SDL.getPixel(isurface, x, y);

                    long b = (color & format.getBmask()) >> format.getBshift();
                    long g = (color & format.getGmask()) >> format.getGshift();
                    long r = (color & format.getRmask()) >> format.getRshift();
                    long a = (color & format.getAmask()) >> format.getAshift();

                    long[] values = filter.apply(r,g,b,a);
                    color = SDL.SDL_MapRGB(bformat,(short)values[0],(short)values[1],(short)values[2]);

                    SDL.setPixel(bsurface,x,y,color);
                }
            }
            format.delete();
            bformat.delete();
        }
        gfx.drawBuffer(buffer,0,0);
        //gfx.drawImage(source,400,0);
    }
}
